import pymysql
from pyecharts.charts import Bar
from pyecharts import options as opts


def get_top_15_voteup():
    # 数据库连接配置
    db_config = {
        'host': 'localhost',
        'port': 3306,
        'user': 'root',
        'password': '123456',
        'database': 'test',
        'charset': 'utf8mb4'
    }
    # 连接数据库
    conn = pymysql.connect(**db_config)
    try:
        with conn.cursor() as cursor:
            # 查询点赞数前十五的记录
            sql = "SELECT UserID, VoteupCount FROM answers_1 ORDER BY VoteupCount DESC LIMIT 15"
            cursor.execute(sql)
            results = cursor.fetchall()
            user_ids = [result[0] for result in results]
            voteup_counts = [result[1] for result in results]
            return user_ids, voteup_counts
    finally:
        conn.close()


def generate_chart():
    user_ids, voteup_counts = get_top_15_voteup()
    bar = (
        Bar()
     .add_xaxis(user_ids)
     .add_yaxis("点赞数", voteup_counts)
     .set_global_opts(
            title_opts=opts.TitleOpts(title="点赞数前十五的回答"),
            xaxis_opts=opts.AxisOpts(axislabel_opts={"rotate": 45}),
            toolbox_opts=opts.ToolboxOpts(is_show=True)
        )
    )
    return bar.render_embed()


if __name__ == "__main__":
    chart_html = generate_chart()
    print(chart_html)